package com.permission.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.base.Preconditions;
import com.permission.beans.PageQuery;
import com.permission.beans.PageResult;
import com.permission.common.RequestHolder;
import com.permission.dao.SysUserMapper;
import com.permission.entity.SysUser;
import com.permission.exception.ParamException;
import com.permission.param.UserParam;
import com.permission.service.SysLogService;
import com.permission.service.SysUserService;
import com.permission.util.BeanValidator;
import com.permission.util.IpUtil;
import com.permission.util.MD5Util;
import com.permission.util.PasswordUtil;

@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

	@Autowired
    private SysUserMapper sysUserMapper;
	
	@Autowired
    private SysLogService sysLogService;
		
	/**
	 * 增加用户
	 */
	public void save(UserParam param) {
		BeanValidator.check(param);
		if(checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
	    if(checkEmailExist(param.getMail(), param.getId())) {
	        throw new ParamException("邮箱已被占用");
	    }
	    String password = PasswordUtil.randomPassword();	    
	    //TODO:
        password = "12345678";
        
        //加密password
        String encryptedPassword = MD5Util.encrypt(password);
        //设置参数
        SysUser user = SysUser.builder().username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .password(encryptedPassword).deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();
        user.setOperator(RequestHolder.getCurrentUser().getUsername());
        user.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        user.setOperateTime(new Date());
        
        // TODO: sendEmail

        sysUserMapper.insertSelective(user);
        sysLogService.saveUserLog(null, user);

	}	
	/**
	 * 检查邮箱是否存在
	 * @param mail
	 * @param userId
	 * @return
	 */
	public boolean checkEmailExist(String mail,Integer userId){
		return sysUserMapper.countByMail(mail, userId) > 0;
	}	
	/**
	 * 检查手机号是否存在
	 * @param mail
	 * @param userId
	 * @return
	 */
	public boolean checkTelephoneExist(String telephone, Integer userId){
		return sysUserMapper.countByTelephone(telephone, userId) > 0;
	}

	/**
	 * 更新用户
	 * （管理员对用户进行的更新，比如用户的手机号或者邮箱换了需要修改的，或者是将用户冻结）
	 * 在这里不需要对密码进行更新，密码是需要用户本人更新的
	 */
	public void update(UserParam param) {
		BeanValidator.check(param);
        if(checkTelephoneExist(param.getTelephone(), param.getId())) {
            throw new ParamException("电话已被占用");
        }
        if(checkEmailExist(param.getMail(), param.getId())) {
            throw new ParamException("邮箱已被占用");
        }
        
        //取出更新之前的用户(记录日志的时候需要记录更新前和更新后的)
        SysUser before = sysUserMapper.selectByPrimaryKey(param.getId());
        //判断要更新的用户是否存在（Preconditions：来源于common工具包）
        Preconditions.checkNotNull(before, "待更新的用户不存在");
        //设置参数
        SysUser after = SysUser.builder().id(param.getId()).username(param.getUsername()).telephone(param.getTelephone()).mail(param.getMail())
                .deptId(param.getDeptId()).status(param.getStatus()).remark(param.getRemark()).build();       
        after.setOperator(RequestHolder.getCurrentUser().getUsername());
        after.setOperateIp(IpUtil.getRemoteIp(RequestHolder.getCurrentRequest()));
        after.setOperateTime(new Date());
        
        sysUserMapper.updateByPrimaryKeySelective(after);
        sysLogService.saveUserLog(before, after);
	}
	/**
	 * 根据邮箱或者手机号码查询用户
	 */
	public SysUser findByKeyword(String keyword) {		
		return sysUserMapper.findByKeyword(keyword);
	}
	/**
	 * 获取所有用户
	 */
	public List<SysUser> getAll() {
		return sysUserMapper.getAll();
	}


    /**
     * 根据部门id获取用户列表
     * @param deptId
     * @param page
     * @return
     */
    public PageResult<SysUser> getPageByDeptId(int deptId, PageQuery page) {
        BeanValidator.check(page);
        int count = sysUserMapper.countByDeptId(deptId);
        if (count > 0) {
            List<SysUser> list = sysUserMapper.getPageByDeptId(deptId, page);
            return PageResult.<SysUser>builder().total(count).data(list).build();
        }
        return PageResult.<SysUser>builder().build();
    }
}
